<template>
	<om-page :title="pageTitle">
		<view class="exam">
			<view class="rbtn">
			    <view class="srbtn" :class="{'acbtn': currentNum > 1 }" @click="getSubjectNum(currentNum-1)">上一题</view>
			    <view class="srbtn next" :class="{'acbtn': currentNum < examInfo.questionResponses.length }" @click="getSubjectNum(currentNum+1)">下一题</view>
			    <button class="sbtn" @click="submitExam">交卷</button>
			</view>
			<view class="answer-box">
			    <view class="answer-show">
			        <view class="answer-type">{{ examInfo.examTitle }}（剩余时长:{{ examTime + examTimeUnit }}）</view>
			        <view class="answer-no" v-show="examInfo.examTypeCode == '38997'">{{ currentNum }} / {{ examInfo.questionResponses.length }}</view>
					<view class="answer-no" v-show="examInfo.examTypeCode == '38996'" style="width: 50px;">
						<picker @change="bindPickerChange" :value="currentNum-1" :range="numArr" style="float: left;font-size: 12px;width: 20px;height:16px;border: 1px solid #CCC;">
							<view class="uni-input">{{numArr[currentNum-1]}}</view>
						</picker>
						<view style="float: left;margin-left: 5px;"> / {{ examInfo.questionResponses.length }}</view>
					</view>
			    </view>
				<view v-for="(item,index) in examInfo.questionResponses" :key="index" v-show="index+1 == currentNum">
					<view class="answer-type-num">{{ item.questionTypeName + '（共' + getNum(item.questionTypeCode) + '题，每题' + getScore(item.questionTypeCode) + '分）' }}</view>
					<view class="answer-tit">{{ (index+1) + '. ' + item.qusetionTitle }}</view>
					<view class="answer-item" v-if="item.questionTypeCode == '38990'">
						<button class="answer-subitem" v-for="(sitem,sindex) in item.choses" :key="sindex" @click="chooseHanle(sindex,item.questionTypeCode)" :class="{'choose' : answerArr[index] == baseCheckArr[sindex]}">{{ sitem }}</button>
					</view>
					<view class="answer-item" v-if="item.questionTypeCode == '38991'">
						<button class="answer-subitem" v-for="(sitem,sindex) in item.choses" :key="sindex" @click="chooseHanle(sindex,item.questionTypeCode)" :class="{'choose' : answerArr[index].indexOf(baseCheckArr[sindex]) > -1}">{{ sitem }}</button>
					</view>
					<view class="answer-item" v-if="item.questionTypeCode == '38992'">
						<button class="answer-subitem" @click="chooseHanle(0,item.questionTypeCode)" :class="{'choose' : answerArr[index] == 'A'}">对</button>
						<button class="answer-subitem" @click="chooseHanle(1,item.questionTypeCode)" :class="{'choose' : answerArr[index] == 'B'}">错</button>
					</view>
					<view class="answer-item" v-if="item.questionTypeCode == '38993'">
						<input type="text" class="text"v-for="sitem in answerArr[index]" placeholder="请输入内容" v-model="sitem.des" />
					</view>
				</view>
			</view>
		</view>
	</om-page>
</template>

<script>
	import { confirmModal } from '@/static/js/common.js';
	import {mapState} from 'pinia';
	import { useLoginUserStore } from '@/stores/login-user.js'
	const app = getApp();
	export default {
		data() {
			return {
				pageTitle:"考试",
				answerArr: [],
				baseCheckArr: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'],
				examId: '',
				getCanExamTime: 0,
				getSubmitTime: 0,
				currentNum: 1,
				numArr: [],
				examTimeCountdown: 0,
				examTime: 0,
				examTimeUnit: '分钟',
				examInfo: {
					examTitle: '',
					examTypeCode: '38996',
					singleNums: 0,
					multipleNums: 0,
					judgeNums: 0,
					fillBlankNums: 0,
					singleScore: 0,
					multipleScore: 0,
					judgeScore: 0,
					fillBlankScore: 0,
					questionResponses: [],
				}
			}	
		},
		computed: {
			...mapState(useLoginUserStore, ['userId', 'userName'])
		},
		methods: {
			chooseHanle(num,code){
				let _that = this;
				if(code == '38990'){
					_that.answerArr[_that.currentNum-1] = _that.baseCheckArr[num]
				}else if(code == '38991'){
					if(_that.answerArr[_that.currentNum-1].indexOf(_that.baseCheckArr[num]) == -1){
						_that.answerArr[_that.currentNum-1].push(_that.baseCheckArr[num])
					}else{
						_that.answerArr[_that.currentNum-1].splice(_that.answerArr[_that.currentNum-1].indexOf(_that.baseCheckArr[num]),1);
					}
				}else if(code == '38992'){
				    _that.answerArr[_that.currentNum-1] = _that.baseCheckArr[num]
				}else{
					
				}
				_that.$forceUpdate()
			},
			bindPickerChange: function(e) {
				this.currentNum = e.detail.value + 1
			},
			getSubjectNum(num){
				let _that = this;
				if(_that.examInfo.examTypeCode == '38996'){
				    if(num<1){
				        _that.currentNum = 1
					}else if(num > _that.examInfo.questionResponses.length){
				        _that.currentNum = _that.examInfo.questionResponses.length
					}else{
				        _that.currentNum = num
					}
				}else{
					if(num == _that.currentNum + 1){
					    if(((_that.examInfo.questionResponses[num-2].questionTypeCode == '38991' || _that.examInfo.questionResponses[num-2].questionTypeCode == '38993') && _that.answerArr[num-2].length>0) || ((_that.examInfo.questionResponses[num-2].questionTypeCode != '38991' && _that.examInfo.questionResponses[num-2].questionTypeCode != '38993') && _that.answerArr[num-2])){
					        if(_that.examInfo.questionResponses[_that.currentNum-1].questionAnswerStr){
					            if(num > _that.examInfo.questionResponses.length){
					                _that.currentNum = _that.examInfo.questionResponses.length
					            }else{
					                _that.currentNum = num
					            }
					        }else{
					            let arr = [];
					            let obj = {};
					            obj.questionId = _that.examInfo.questionResponses[num-2].id
					            obj.answer = _that.answerArr[num-2] instanceof Array ? ( _that.examInfo.questionResponses[num-2].questionTypeCode == '38993' ? _that.answerArr[num-2].map(e => e.des).join('|') : _that.answerArr[num-2].sort().join('|')) : _that.answerArr[num-2]
					            obj.examId = _that.examId
					            arr.push(obj)
								
								_that.om.request("exam/checkAnswer", {
									asnwers: JSON.stringify(arr)
								}).then(res=>{
									if (res.succeed) {
										if(num > _that.examInfo.questionResponses.length){
										    _that.currentNum = _that.examInfo.questionResponses.length
										}else{
										    _that.currentNum = num
										}
																				
										if(num > _that.examInfo.questionResponses.length){
											confirmModal(_that, '提示信息', '您已完成考试,将关闭页面!', () => {
												uni.redirectTo({
													url: '/pages/mine/exam/exam-list'
												});
											})
										}	
									}else{
										_that.om.toast(res.msg);
									}
								})
					        }
					    }else{
							confirmModal(_that, '提示信息', '当前题目未完成，是否继续提交?', () => {
					            if(num > _that.examInfo.questionResponses.length){
					                _that.currentNum = _that.examInfo.questionResponses.length
					            }else{
					                _that.currentNum = num
					            }
								
								_that.om.request("exam/checkAnswer", {
									asnwers: JSON.stringify([{
									    questionId: _that.examInfo.questionResponses[num-2].id,
									    answer: '',
									    examId: _that.examId
									}]),
								}).then(res=>{
									if (res.succeed) {
										if(num > _that.examInfo.questionResponses.length){
										    confirmModal(_that, '提示信息', '您已完成考试,将关闭页面!', () => {
										    	uni.redirectTo({
										    		url: '/pages/mine/exam/exam-list'
										    	});
										    })
										}
									}else{
										_that.om.toast(res.msg);
									}
								})
					        })
					    }
					}else{
						_that.om.toast("竞答考试仅支持选择下一题！");
					}					
				}
			},
			getNum(code){
			    let num = 0;
			    if(code == '38990'){
			        num = this.examInfo.singleNums
			    }else if(code == '38991'){
			        num = this.examInfo.multipleNums
			    }else if(code == '38992'){
			        num = this.examInfo.judgeNums
			    }else if(code == '38993'){
			        num = this.examInfo.fillBlankNums
			    }else{
			        // num = this.examInfo.shortAnswerNums
			    }
			    return num;
			},
			getScore(code){
			    let score = 0;
			    if(code == '38990'){
			        score = this.examInfo.singleScore
			    }else if(code == '38991'){
			        score = this.examInfo.multipleScore
			    }else if(code == '38992'){
			        score = this.examInfo.judgeScore
			    }else if(code == '38993'){
			        score = this.examInfo.fillBlankScore
			    }else{
			        // score = this.examInfo.shortAnswerScore
			    }
			    return score;
			},
			submitExam(){
				let _that = this;
				let answerList = [];
				let isValuable = true
				if(_that.examInfo.examTypeCode == '38996') {
				    for (let i = 0; i < _that.answerArr.length; i++) {
				        if (((_that.examInfo.questionResponses[i].questionTypeCode == '38991' || _that.examInfo.questionResponses[i].questionTypeCode == '38993') && _that.answerArr[i].length > 0) || ((_that.examInfo.questionResponses[i].questionTypeCode != '38991' && _that.examInfo.questionResponses[i].questionTypeCode != '38993') && _that.answerArr[i])) {
				
				        } else {
							isValuable = false
						}
				
						let obj = {};
						obj.questionId = _that.examInfo.questionResponses[i].id
						obj.answer = _that.answerArr[i] instanceof Array ? ( _that.examInfo.questionResponses[i].questionTypeCode == '38993' ? _that.answerArr[i].map(e => e.des).join('|') : _that.answerArr[i].sort().join('|')) : _that.answerArr[i]
						obj.examId = _that.examId
						answerList.push(obj)
					}
				}else{
				    let obj = {};
				    obj.questionId = _that.examInfo.questionResponses[_that.currentNum-1].id
				    obj.answer = _that.answerArr[_that.currentNum-1] instanceof Array ? ( _that.examInfo.questionResponses[_that.currentNum-1].questionTypeCode == '38993' ? _that.answerArr[_that.currentNum-1].map(e => e.des).join('|') : _that.answerArr[_that.currentNum-1].sort().join('|')) : _that.answerArr[_that.currentNum-1]
				    obj.examId = _that.examId
					if (((_that.examInfo.questionResponses[_that.currentNum-1].questionTypeCode == '38991' || _that.examInfo.questionResponses[_that.currentNum-1].questionTypeCode == '38993') && _that.answerArr[_that.currentNum-1].length > 0) || ((_that.examInfo.questionResponses[_that.currentNum-1].questionTypeCode != '38991' && _that.examInfo.questionResponses[_that.currentNum-1].questionTypeCode != '38993') && _that.answerArr[_that.currentNum-1])) {
					
					} else {
					    isValuable = false
					}
				    answerList.push(obj)
				}
				
				if(isValuable){
					if(_that.canSubmitExam()){
						_that.om.request("exam/checkAnswer", {
							asnwers: JSON.stringify(answerList)
						}).then(res=>{
							if (res.succeed) {
								if(_that.examInfo.examTypeCode == '38996'){
									confirmModal(_that, '提示信息', '试卷提交成功,将关闭页面!', () => {
										uni.redirectTo({
											url: '/pages/mine/exam/exam-list'
										});
									})
								}else{
									if(_that.currentNum == _that.examInfo.questionResponses.length){
										confirmModal(_that, '提示信息', '您已完成考试,将关闭页面!', () => {
											uni.redirectTo({
												url: '/pages/mine/exam/exam-list'
											});
										})
									}
								}
							}else{
								_that.om.toast(res.msg);
							}
						})
					}
				}else{
					confirmModal(_that, '提示信息', (_that.examInfo.examTypeCode == '38996' ? '你有' : '当前')+'题目未完成，是否继续提交?', () => {
						if(_that.canSubmitExam()){
							_that.om.request("exam/checkAnswer", {
								asnwers: JSON.stringify(answerList)
							}).then(res=>{
								if (res.succeed) {
									if(_that.examInfo.examTypeCode == '38996'){
										confirmModal(_that, '提示信息', '试卷提交成功,将关闭页面!', () => {
											uni.redirectTo({
												url: '/pages/mine/exam/exam-list'
											});
										})
									}else{
										if(_that.currentNum == _that.examInfo.questionResponses.length){
											confirmModal(_that, '提示信息', '您已完成考试,将关闭页面!', () => {
												uni.redirectTo({
													url: '/pages/mine/exam/exam-list'
												});
											})
										}
									}
								}else{
									_that.om.toast(res.msg);
								}
							})
						}
					})
				}
			},
			canSubmitExam(){
				let _that = this;
				let canSubmit = false;
				if(_that.examInfo.examTypeCode == '38996'){
				    let endTime = _that.examInfo.examEndTime
				    let now_time = Date.parse(new Date());//当前时间的时间戳
				    let end_time = Date.parse(new Date(endTime));//指定时间的时间戳
				    let time_dis = (end_time - now_time)/1000;
				    if(time_dis > _that.getSubmitTime * 60){
						_that.om.toast("只能提前" + _that.getSubmitTime + "分钟提交考卷！");
				    }else{
				        canSubmit = true
				    }
				}else{
				    canSubmit = true
				}
				return canSubmit
			},
			disTime(){
				let _that = this;
				let now_time = Date.parse(new Date());//当前时间的时间戳
				let end_time = Date.parse(new Date(_that.examInfo.examEndTime));//指定时间的时间戳
				if(end_time < now_time){
				    //考试已结束
				    return false
				}else{
				    let time_dis = (end_time - now_time)/1000;
				    _that.examTimeCountdown = time_dis
				    _that.countTime()
				}
			},
			countTime(){
				let _that = this;
				_that.examTimeCountdown -= 1
				if(_that.examTimeCountdown ==0){
				    _that.examTime = 0
				    let answerList = [];
				    for (let i = 0; i < _that.answerArr.length; i++) {
				        let obj = {};
				        obj.questionId = _that.examInfo.questionResponses[i].id
				        obj.answer = _that.answerArr[i] instanceof Array ? (_that.examInfo.questionResponses[i].questionTypeCode == '38993' ? _that.answerArr[i].map(e => e.des).join('|') : _that.answerArr[i].sort().join('|')) : _that.answerArr[i]
				        obj.examId = _that.examId
				        answerList.push(obj)
				    }
					
					_that.om.request("exam/checkAnswer", {
						asnwers: JSON.stringify(answerList)
					}).then(res=>{
						if (res.succeed) {
							confirmModal(_that, '提示信息', '考试时间已结束，系统已自动提交考卷,将关闭页面!', () => {
								uni.redirectTo({
									url: '/pages/mine/exam/exam-list'
								});
							})
						}else{
							_that.om.toast(res.msg);
						}
					})
				}else if(_that.examTimeCountdown<60){
				    _that.examTime = _that.examTimeCountdown
				    _that.examTimeUnit = '秒'
				}else{
				    _that.examTime = Math.ceil(_that.examTimeCountdown/60)
				    _that.examTimeUnit = '分钟'
				}
				
				if(_that.examTimeCountdown > 0){
				    setTimeout(_that.countTime,1000);
				}
			}
		},
		onLoad(options) {
			let _that = this;
			_that.examId = options.id
			let arr = [_that.om.request("/dataDict/getIntByCode",{code: 'DD033010001'}), 
			_that.om.request("/dataDict/getIntByCode",{code: 'DD033010002'}),
			 _that.om.request("/exam/selectById",{id: _that.examId})]
			//多个AJAX全部完成时开始执行
			Promise.all(arr).then(res => {
				_that.getCanExamTime = res[0].value
				_that.getSubmitTime = res[1].value
				_that.examInfo = res[2].value
				
				for(let i=0; i<_that.examInfo.questionResponses.length;i++){
					_that.numArr.push(i+1)
					_that.answerArr.push((_that.examInfo.questionResponses[i].questionTypeCode == '38991' || _that.examInfo.questionResponses[i].questionTypeCode == '38993') ? [] : '')
				    if(_that.examInfo.questionResponses[i].questionTypeCode == '38993'){
				        for(let m=0; m<_that.examInfo.questionResponses[i].answerNums;m++){
				            _that.answerArr[i].push({des: ''})
				        }
				    }
				}
				_that.disTime()
			})
		},
		onShow() {
			
		}
	};
</script>

<style lang="scss" scoped>
	.exam{
		display: flex;
		display: -webkit-flex;
		flex-direction: column;
		height: 100%;
		width: 100%;
		top: 0;
		left: 0;
		position: absolute;
		background: url("") center no-repeat;
		background-size: 100% 260px;
		background-position: 0 -35px;
		.rbtn{
		    position: absolute;
		    left: 50%;
			top: 10px;
			width: 242px;
			margin-left: -121px;
			.srbtn{
				float: left;
				line-height: 30px;
				font-weight:500;
				font-size:14px;
				width:70px;
				text-align: center;
			}
		    .next{
		        margin-left: 16px;
		    }
			.acbtn{
				background:rgba(65,149,253,1);
				border-radius:15px;
				font-weight:800;
				font-size:12px;
				color: #FFF;
			}
		    .sbtn{
		        float: left;
		        width:70px;
		        height:30px;
		        line-height: 30px;
		        text-align: center;
		        background:#FFF;
		        border-radius:15px;
		        font-weight:800;
		        font-size:12px;
		        color: #4195FD;
		        margin-left: 16px;
		    }
		}
		.answer-box{
		    margin: 50px 15px 20px;
		    position: relative;
		    background: #FFF;
		    padding: 0 20px;
		    box-shadow: 1px 7px 20px 0px rgba(0,95,213,0.2);
		    border-radius: 15px;
		    .answer-show{
		        height: 20px;
		        margin: 25px 0;
		        .answer-type{
		            float: left;
		            font-weight:800;
		            font-size:16px;
		            color: #111111;
		            padding-left: 28px;
		            background: url("") no-repeat;
		            background-size: 20px 20px;
		            line-height: 20px;
		        }
		        .answer-no{
		            float: right;
		            width: 25px;
		            height: 18px;
		            line-height: 18px;
		            text-align: center;
		            font-weight:500;
		            color: #111111;
		            font-size:12px;
		            border-bottom: 2px solid #111111;
		        }
		    }
			.answer-type-num{
				margin-bottom: 10px;
			}
		    .answer-tit{
		        font-size:18px;
		        font-weight: bold;
		        line-height: 24px;
		        color: #000;
		        margin-bottom: 31px;
		    }
		    .answer-item{
		        padding-bottom: 41px;
		        .answer-subitem{
		            height: 45px;
		            line-height: 45px;
		            background: #C4DEFF;
		            border-radius: 22px;
		            padding: 0 40px;
		            color: #4296FE;
		            font-size:16px;
		            font-weight: bold;
		            margin-bottom: 15px;
		            text-align: left;
		        }
		        .answer-subitem:after{
		            border: 0;
		        }
		        .answer-subitem.choose{
		            background: #4296FE;
		            color: #FFF;
		        }
		        .answer-subitem.correct{            
		            background:rgba(211,252,229,1) url("") no-repeat;
		            background-size: 19px 13px;
		            background-position: 257px 16px;
		            border:2px solid rgba(51,209,121,1);
		            color: #33D179;
		        }
		        .answer-subitem.wrong{
		            background:rgba(248,230,231,1) url("") no-repeat;
		            background-size: 15px 15px;
		            background-position: 257px 15px;
		            border:2px solid rgba(232,40,90,1);
		            color: #E8285A;
		        }
		        .text{
		            width: 100%;
		            height: 45px;
		            background: #f9f9fb;
		            margin-bottom: 15px;
		            border-radius: 10px;
		            line-height: 45px;
		            padding: 8px;
		            box-sizing: border-box;
		        }
		    }
		}
	}
</style>